<template>
  <div class="channel-edit">
    <van-cell title="我的频道" :border="false">
      <van-button size="small" round type="danger" plain @click='isEdit = !isEdit'>{{isEdit?'完成':'编辑'}}</van-button>
    </van-cell>
    <van-grid :gutter="10">
      <van-grid-item :class="{active: active === index}" class="channel-item" v-for="(item,index) in channels"
        :key="item.id" :icon="isEdit && item.name!=='推荐'?'close':''" :text='item.name'
        @click='mychannelClick(index,item.id)' />
    </van-grid>
    <van-cell title="频道推荐" :border="false"></van-cell>
    <van-grid :gutter="10">
      <van-grid-item class="channel-item" v-for="item in recommendChannels" :key="item.id" :text="item.name" icon="plus"
        @click='recommintClick(item)' />
    </van-grid>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { setItem } from '@/utils/seccession.js'
import { addUserChannels, deleteUserChannel } from '@/api/channels.js'
export default {
  name: 'ChannelEdit',
  components: {},
  props: ['channels', 'active', 'allChannels'],
  data () {
    return {
      isEdit: false
    }
  },
  computed: {
    ...mapState(['user']),
    recommendChannels () {
      return this.allChannels.filter(channel => {
        return this.channels.every(myChannel => channel.id !== myChannel.id)
      })
    }
  },
  watch: {},
  created () {

  },
  mounted () { },
  methods: {
    async mychannelClick (i, id) {
      if (!this.isEdit) this.$emit('ChannelState', false, i)
      if (i < this.active && i !== 0) {
        this.$emit('ChannelState', true, this.active - 1)
      }
      this.channels.splice(i, 1)
      if (this.user) {
        await deleteUserChannel(id)
      } else {
        setItem('hmtt_channel', this.channels)
      }
    },
    async recommintClick (item) {
      this.channels.push(item)
      if (this.user) {
        await addUserChannels({
          id: item.id,
          seq: this.channels.length
        })
      } else {
        setItem('hmtt_channel', this.channels)
      }
    }
  }
}
</script>

<style scoped lang="less">
.channel-edit {
  .van-grid {
    /deep/.active {
      .van-grid-item__text {
        color: red !important;
      }
    }
  }
  .channel-item {
    height: 86px;
    /deep/ .van-icon-close {
      position: absolute;
      right: -10px;
      top: -10px;
      font-size: 36px;
      color: #ccc;
    }
    /deep/ .van-grid-item__content {
      background-color: #f5f5f6;
      .active {
        color: red;
      }
      .van-grid-item__text {
        color: #222;
        font-size: 28px;
        margin-top: 0;
      }
      flex-direction: row;
      color: #222;
      .van-icon {
        font-size: 24px;
      }
    }
  }
}
</style>
